package com.qingke.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qingke.annotation.SkipSecurityCheck;
import com.qingke.pojo.Classes;
import com.qingke.pojo.Employee;
import com.qingke.pojo.EmployeeAccount;
import com.qingke.pojo.EmployeeJurisdiction;
import com.qingke.pojo.InClassTeacher;
import com.qingke.pojo.Jurisdiction;
import com.qingke.pojo.Student;
import com.qingke.pojo.StudentAccount;
import com.qingke.service.ClassService;
import com.qingke.service.EmployeeService;
import com.qingke.service.InClassTeacherService;
import com.qingke.service.JurisdictionService;
import com.qingke.service.StudentService;

@Controller
@RequestMapping("/admin")
public class AdminController {
	private static Logger logger = Logger.getLogger(AdminController.class);
	private static final String password = "123456";
	private Map<String, Object> map;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private JurisdictionService jurisdictionService;
	@Autowired
	private InClassTeacherService inClassTeacherService;
	@Autowired
	private ClassService classService;

	@RequestMapping("getAdmin")
	@SkipSecurityCheck
	@ResponseBody
	public Map getAdmin(HttpServletRequest request, ModelMap modelMap) {
		// int id =Integer.valueOf(request.getParameter("id"));
		HttpSession se = request.getSession();
		Employee admin = (Employee) se.getAttribute("user");
		// se.setAttribute("admin", admin);
		logger.info("get Admin[" + admin + "]");
		map = new HashMap();
		map.put("admin", admin);
		return map;
	}

	@RequestMapping("updateAdminMessage")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateAdminMeassge(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		Employee admin = (Employee) se.getAttribute("user");
		String userId = request.getParameter("user_id");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		logger.info("get AdminMessage[" + "userId=" + userId + ",email=" + email + ",phone=" + phone + "]");
		if (!userId.equals(admin.getEmployeeNumber())) {
			map.put("isSame", "no");
		} else {
			admin.setEmail(email);
			admin.setPhone(phone);
			int count = employeeService.updateEmployeeByPrimaryKey(admin);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "failed");
			}
		}
		Collection<Object> c = map.values();
		Iterator it = c.iterator();
		for (; it.hasNext();) {
			System.out.println(it.next());
		}
		return map;
	}

	@RequestMapping("updateAdminPassword")
	@SkipSecurityCheck
	@ResponseBody
	public Map updatePssword(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String oldPassword = request.getParameter("old_password");
		String newPassword = request.getParameter("new_password");
		String confrimPassword = request.getParameter("confirm_password");
		logger.info("get AdminPassword:old_password" + oldPassword + ",new_password=" + newPassword
				+ ",confirm_password=" + confrimPassword);
		HttpSession se = request.getSession();
		Employee admin = (Employee) se.getAttribute("user");
		EmployeeAccount employeeAccount = employeeService.getEmployeeAccountById(admin.getId());
		if (!oldPassword.equals(employeeAccount.getPassword())) {
			map.put("isExsit", "false");
		} else if (!newPassword.equals(confrimPassword)) {
			map.put("equal", "false");
		} else {
			employeeAccount.setPassword(newPassword);
			int count = employeeService.updateEmployeeAccountByPrimaryKey(employeeAccount);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "false");
			}
		}
		Collection<Object> c = map.values();
		Iterator it = c.iterator();
		for (; it.hasNext();) {
			System.out.println(it.next());
		}
		return map;
	}

	@RequestMapping("listUser")
	@SkipSecurityCheck
	@ResponseBody
	public Map listUser(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		List<Employee> employee = new ArrayList();
		List<Student> student = new ArrayList();
		List<Employee> employees = employeeService.listEmployee();
		for (Employee em : employees) {
			if (!em.getIsDeleted()) {
				employee.add(em);
				logger.info("get employeeIsDeleted:" + em.getIsDeleted());
			}
			map.put("employee", employee);
		}
		List<Student> students = studentService.listStudent();
		for (Student st : students) {
			if (!st.getIsDeleted()) {
				student.add(st);
				logger.info("get stduentIsDeleted:" + st.getIsDeleted());
			}
			map.put("student", student);
		}
		return map;
	}

	@RequestMapping("getUser")
	@SkipSecurityCheck
	@ResponseBody
	public Map getUser(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		String userId = (String) request.getParameter("user_id");
		logger.info("get userId=" + userId);
		if (userId.contains("E")) {
			Employee employee = employeeService.getEmployeeeByEmployeeNumber(userId);
			logger.info("get employee:" + employee.getName());
			se.setAttribute("employee", employee);
			map.put("Employee", employee);
		} else {
			Student student = studentService.getStudentByStudentNumber(userId);
			logger.info("get student:" + student.getName());
			se.setAttribute("student", student);
			map.put("Student", student);
		}
		return map;

	}

	@RequestMapping("deleteUser")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteUser(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String userId = (String) request.getParameter("user_id");
		logger.info("get userId=" + userId);
		if (userId.contains("E")) {
			Employee employee = employeeService.getEmployeeeByEmployeeNumber(userId);
			int count = employeeService.softDeleteEmployee(employee.getId());
			if (count > 0) {
				map.put("isDelete", "success");
			} else {
				map.put("isDelete", "failed");
			}
		} else {
			Student student = studentService.getStudentByStudentNumber(userId);
			int count = studentService.softDeleteEmployee(student.getId());
			if (count > 0) {
				map.put("isDelete", "success");
			} else {
				map.put("isDelete", "failed");
			}
		}
		return map;

	}

	@RequestMapping("updateUser")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateUser(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String userId = (String) request.getParameter("user_id");
		String name = (String) request.getParameter("name");
		String position = (String) request.getParameter("position");
		logger.info("get user:userId=" + userId + ",name=" + name + ",position=" + position);
		HttpSession se = request.getSession();
		if (userId.contains("E")) {
			Employee em = (Employee) se.getAttribute("employee");
			System.out.println("employee:" + em);
			Employee employee = employeeService.getEmployeeeByEmployeeNumber(userId);
			EmployeeJurisdiction emJurisdiction = employeeService.getEmployeeJurisdictionByEmployeeId(employee.getId());
			Jurisdiction jurisdiction = jurisdictionService.getJurisdictionByName(position);
			if ("学员".equals(position)) {
				map.put("type", "false");
			} else if (!userId.equals(em.getEmployeeNumber())) {
				map.put("isSame", "no");
			} else {
				employee.setName(name);
				int count1 = employeeService.updateEmployeeByPrimaryKey(employee);
				emJurisdiction.setJurisdictionId(jurisdiction.getId());
				int count2 = employeeService.updateEmployeeJurisdictionByPrimaryKey(emJurisdiction);
				logger.info("get count1:" + count1);
				logger.info("get count2:" + count2);
				if (count1 > 0 || count2 > 0) {
					map.put("success", "true");
				} else {
					map.put("success", "false");
				}
			}
		} else if (userId.contains("S")) {
			Student student = studentService.getStudentByStudentNumber(userId);
			Student st = (Student) se.getAttribute("student");
			logger.info("get student:" + st.getName());
			if (!"学员".equals(position)) {
				map.put("type", "false");
			} else if (!userId.equals(st.getStudentNumber())) {
				map.put("isSame", "no");
			} else {
				student.setName(name);
				int count = studentService.updateStudentByPrimaryKey(student);
				logger.info("get count:" + count);
				if (count > 0) {
					map.put("success", "true");
				} else {
					map.put("success", "true");
				}
			}
		}
		return map;
	}

	@RequestMapping("createUser")
	@SkipSecurityCheck
	@ResponseBody
	public Map createUser(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String userId = (String) request.getParameter("user_id");
		String name = (String) request.getParameter("name");
		String position = (String) request.getParameter("position");
		logger.info("get user:userId=" + userId + ",name=" + name + ",position=" + position);
		if (userId.contains("E")) {
			if ("学员".equals(position)) {
				map.put("type", "false");
			} else if (employeeService.getEmployeeeByEmployeeNumber(userId) != null) {
				map.put("isExist", "yes");
			} else {
				Employee employee = new Employee();
				EmployeeAccount employeeAccount = new EmployeeAccount();
				EmployeeJurisdiction employeeJurisdiction = new EmployeeJurisdiction();
				Jurisdiction jurisdiction = jurisdictionService.getJurisdictionByName(position);
				Date date = new Date();
				Timestamp timeStamp = new Timestamp(date.getTime());
				System.out.println(timeStamp);
				employee.setEmployeeNumber(userId);
				employee.setName(name);
				employee.setHiredate(timeStamp);
				employee.setIsDeleted(false);
				int count1 = employeeService.saveEmployee(employee);
				if (count1 > 0) {
					Employee em = employeeService.getEmployeeeByEmployeeNumber(userId);
					employeeAccount.setId(em.getId());
					employeeAccount.setPassword(password);
					int count2 = employeeService.saveEmployeeAccount(employeeAccount);
					employeeJurisdiction.setEmployeeId(employee.getId());
					employeeJurisdiction.setJurisdictionId(jurisdiction.getId());
					int count3 = employeeService.saveEmployeeJurisdiction(employeeJurisdiction);
					if (count2 > 0 || count3 > 0) {
						map.put("success", "true");
					}
				} else {
					map.put("success", "false");
				}
			}
		} else if (userId.contains("S")) {
			if (!"学员".equals(position)) {
				map.put("type", "false");
			} else if (studentService.getStudentByStudentNumber(userId) != null) {
				map.put("isExist", "yes");
			} else {
				Student student = new Student();
				StudentAccount studentAccount = new StudentAccount();
				student.setStudentNumber(userId);
				student.setName(name);
				student.setLearnStatusId(1);
				student.setIsDeleted(false);
				int count = studentService.saveStudent(student);
				if (count > 0) {
					Student st = studentService.getStudentByStudentNumber(userId);
					studentAccount.setId(st.getId());
					studentAccount.setPassword(password);
					int count1 = studentService.saveStudentAccount(studentAccount);
					if (count1 > 0) {
						map.put("success", "true");
					}
				} else {
					map.put("success", "true");
				}
			}
		}
		return map;
	}

	@RequestMapping("listStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map listStudent(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		List<Student> student = new ArrayList();
		List<Student> students = studentService.listStudent();

		List<InClassTeacher> inClassTeacher = inClassTeacherService.listInClassTeacher();
		if(students!=null){
			for (Student st : students) {
				logger.info("list student:" + st);
				if (!st.getIsDeleted()) {
					student.add(st);
				}
				map.put("student", student);
			}
		}
		if(inClassTeacher!=null){
			for (InClassTeacher ict : inClassTeacher) {
				logger.info("list inClassTeacher:" + ict);
			}
			map.put("inClassTeacher", inClassTeacher);
		}else{
			map.put("stduent", "");
			map.put("inClassTeacher", "");
		}
		return map;
	}

	@RequestMapping("getStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map getStudent(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		String student_id = (String) request.getParameter("student_id");
		logger.info("get studentId:" + student_id);
		Student student = studentService.getStudentByStudentNumber(student_id);
		se.setAttribute("student", student);
		map.put("Student", student);
		return map;

	}

	@RequestMapping("deleteStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteStudent(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String student_id = (String) request.getParameter("student_id");
		logger.info("get studentId:" + student_id);
		Student student = studentService.getStudentByStudentNumber(student_id);
		int count = studentService.softDeleteEmployee(student.getId());
		if (count > 0) {
			map.put("isDelete", "success");
		} else {
			map.put("isDelete", "failed");
		}
		return map;
	}

	@RequestMapping("updateStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateStudent(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String studentId = (String) request.getParameter("student_id");
		String name = (String) request.getParameter("name");
		String className = (String) request.getParameter("class_name");
		String email = (String) request.getParameter("email");
		String phone = (String) request.getParameter("phone");
		String teacherName = (String) request.getParameter("teacher_name");
		HttpSession se = request.getSession();
		Student st = (Student) se.getAttribute("student");
		logger.info("get student:stduentId=" + studentId + ",name=" + name + ",className=" + className + ",email="
				+ email + ",phone=" + phone + ",teacherName=" + teacherName);
		Student student = studentService.getStudentByStudentNumber(studentId);
		Classes clazz = classService.getClassByClassName(className);
		Employee teacher = employeeService.getEmployeeByName(teacherName);
		if (!studentId.equals(st.getStudentNumber())) {
			map.put("isSame", "no");
		} else if (clazz == null) {
			map.put("isClassExist", "no");
		} else if (teacher == null) {
			map.put("isTeacherExist", "no");
		} else if (!inClassTeacherService.isTeacherInClass(teacher.getId(), clazz.getId())) {
			map.put("teacherInClass", "no");
		} else {
			student.setName(name);
			student.setClassId(clazz.getId());
			student.setEmail(email);
			student.setPhone1(phone);
			int count = studentService.updateStudentByPrimaryKey(student);
			if (count > 0) {
				map.put("success", "true");
			} else {
				map.put("success", "true");
			}
		}
		return map;
	}

	@RequestMapping("createStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map createStudent(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String studentId = (String) request.getParameter("student_id");
		String name = (String) request.getParameter("name");
		String className = (String) request.getParameter("class_name");
		String email = (String) request.getParameter("email");
		String phone = (String) request.getParameter("phone");
		String teacherName = (String) request.getParameter("teacher_name");
		logger.info("get student:stduentId=" + studentId + ",name=" + name + ",className=" + className + ",email="
				+ email + ",phone=" + phone + ",teacherName=" + teacherName);
		Classes clazz = classService.getClassByClassName(className);
		Employee teacher = employeeService.getEmployeeByName(teacherName);
		if (studentService.getStudentByStudentNumber(studentId) != null) {
			map.put("isExist", "yes");
		} else if (clazz == null) {
			map.put("isClassExist", "no");
		} else if (teacher == null) {
			map.put("isTeacherExist", "no");
		} else if (!inClassTeacherService.isTeacherInClass(teacher.getId(), clazz.getId())) {
			map.put("teacherInClass", "no");
		} else {
			Student student = new Student();
			StudentAccount studentAccount = new StudentAccount();
			student.setStudentNumber(studentId);
			student.setName(name);
			student.setClassId(clazz.getId());
			student.setEmail(email);
			student.setPhone1(phone);
			student.setLearnStatusId(1);
			student.setIsDeleted(false);
			int count = studentService.saveStudent(student);
			if (count > 0) {
				Student st = studentService.getStudentByStudentNumber(studentId);
				studentAccount.setId(st.getId());
				studentAccount.setPassword(password);
				int count1 = studentService.saveStudentAccount(studentAccount);
				if (count1 > 0) {
					map.put("success", "true");
				}
			} else {
				map.put("success", "true");
			}
		}
		return map;
	}

}
